package com.xl.utils.util.redissonlock.config;

import com.sun.xml.internal.bind.v2.TODO;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author xionglin
 * @date 2021/5/15 20:43
 * @Description redisson配置
 */
@Configuration
//配置xl.redissonlcok.enabled:true时才加载这个配置文件
@ConditionalOnProperty("xl.redissonlcok.enabled")
public class RedissonConfig {


    @Value("${xl.redissonlcok.cluster:false}")
    public boolean cluster;
    /**
     * 单机模式格式为：redis://192.168.37.134:7001 ,集群模式格式由逗号隔开如：redis://192.168.37.134:7001,redis://192.168.37.134:7002,redis://192.168.37.134:7003
     */
    @Value("${xl.redissonlcok.cluster.hosts}")
    public String clusterHosts;
    @Value("${xl.redissonlcok.host:127.0.0.1}")
    public String host;
    @Value("${xl.redissonlcok.password}")
    public String password;

    @Bean
    public RedissonClient redissionClient() {
        Config config = new Config();
        //TODO 这里不止是由集群模式和单机模式，还有哨兵和主从两种，这两种先不考虑
        if (cluster) {
            //连接集群redis
            if (StringUtils.isBlank(clusterHosts)) {
                throw new RuntimeException("host配置有问题");
            }
            ClusterServersConfig clusterServersConfig = config.useClusterServers();
            List<String> addresses = getAddresses(clusterHosts);
            for (String host : addresses) {
                clusterServersConfig.addNodeAddress(host);
            }
            return Redisson.create(config);
        } else {
            //连接单机redis
            SingleServerConfig singleServerConfig = config.useSingleServer().setAddress(host);
            if (StringUtils.isNotBlank(password)) {
                singleServerConfig.setPassword(password).setDatabase(0);
            }
            return Redisson.create(config);
        }
    }

    /**
     * clusterHosts：逗号分隔
     * @param clusterHosts
     * @return
     */
    private List<String> getAddresses(String clusterHosts) {
        String[] split = clusterHosts.split(",");
        List<String> list = new ArrayList<>(Arrays.asList(split));
        return list;
    }




}
